<template>
  <div class="comment-container">
    <div class="comment-header">
      <h2>评论管理</h2>
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="商品ID">
          <el-input
            v-model="filterForm.goodsId"
            placeholder="输入商品ID筛选"
            clearable
            @clear="handleFilter"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
          v-loading="loading"
          :data="paginatedCommentList"
          style="width: 100%"
          border
          max-height="600"
          :scrollbar-always-on="true"
        >
          <el-table-column prop="goodsId" label="商品ID" width="80" />
          <el-table-column label="商品图片" width="120" align="center">
            <template #default="{ row }">
              <el-image 
                v-if="row.goodsImg"
                :src="row.goodsImg" 
                style="width: 80px; height: 80px; object-fit: cover;"
                :preview-src-list="[row.goodsImg]"
                fit="cover"
              />
              <span v-else>暂无图片</span>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.goodsName || '未知商品' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="orderId" label="订单ID" width="100" />
      <el-table-column prop="content" label="评论内容" min-width="300" show-overflow-tooltip />
      <el-table-column prop="size" label="尺码" width="80" align="center" />
      <el-table-column prop="color" label="颜色" width="80" align="center" />
      <el-table-column label="发布时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.create_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="60" fixed="right">
        <template #default="{ row }">
          <el-button
            type="danger"
            link
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllComments, getProductComments, deleteComment } from '../../api/comment'

const router = useRouter()
const loading = ref(false)
const commentList = ref([])
const filterForm = ref({
  goodsId: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分页后的评论列表
const paginatedCommentList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return commentList.value.slice(start, end)
})

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

// 处理评论数据
const processCommentData = (comments) => {
  return comments.map(comment => {
    return {
      ...comment,
      // 确保商品图片和名称字段存在
      goodsImg: comment.goodsImg || '',
      goodsName: comment.goodsName || '未知商品'
    }
  })
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  try {
    const date = new Date(time)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
  } catch (e) {
    console.error("时间格式化错误:", e)
    return time
  }
}

// 获取评论列表
const fetchCommentList = async () => {
  try {
    loading.value = true
    const res = filterForm.value.goodsId
      ? await getProductComments(filterForm.value.goodsId)
      : await getAllComments()
    
    if (res.status === 0) {
      // 处理评论数据
      commentList.value = processCommentData(res.data)
      // 更新总数
      total.value = commentList.value.length
      // 重置到第一页
      currentPage.value = 1
    } else {
      ElMessage.error(res.message || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表错误:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 删除评论
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这条评论吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteComment(row.id)
      if (res.status === 0) {
        ElMessage.success('删除评论成功')
        await fetchCommentList()
      } else {
        ElMessage.error(res.message || '删除评论失败')
      }
    } catch (error) {
      console.error('删除评论错误:', error)
      ElMessage.error('删除评论失败')
    }
  }).catch(() => {})
}



// 筛选处理
const handleFilter = () => {
  fetchCommentList()
}

onMounted(() => {
  fetchCommentList()
})
</script>

<style scoped>
.comment-container {
  padding: 20px;
}

.comment-header {
  margin-bottom: 20px;
}

.comment-header h2 {
  margin: 0 0 20px 0;
  font-size: 20px;
  color: #333;
}

.filter-form {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
}
</style>